goog.require('goog.array');
goog.require('goog.debug.DivConsole');
goog.require('goog.debug.Logger');
goog.require('goog.debug.LogManager');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.object');
goog.require('goog.style');
goog.require('goog.ui.Button');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.Option');
goog.require('goog.ui.SelectionModel');
goog.require('goog.ui.Separator');
goog.require('goog.ui.Toolbar');
goog.require('goog.ui.ToolbarRenderer');
goog.require('goog.ui.ToolbarButton');
goog.require('goog.ui.ToolbarMenuButton');
goog.require('goog.ui.ToolbarSelect');
goog.require('goog.ui.ToolbarSeparator');
goog.require('goog.ui.ToolbarToggleButton')
goog.require('goog.Timer');
goog.require('goog.Delay');
goog.require('goog.ui.tree.TreeControl');
goog.require('goog.ui.TableSorter');



function InstallFunction(obj,functionName)
{
  obj[functionName] = function() { Request(functionName,arguments,'/browse/rpc'); }
}

var entities_tree,work_data,clipboardNode,logger,logconsole;
var EVENTS;

var server = {};
InstallFunction(server,'getWorks');
InstallFunction(server,'getEntityList');
InstallFunction(server,'getEntities');

function getEntityListing(entity_name)
{
  server.getEntityListing(entity_name,getEntityListingSuccess);
}

function getEntityList(entity_name)
{
  server.getEntityList(entity_name,getEntityListSuccess);
}

function getEntityListSuccess(response)
{
  entities_tree = new goog.ui.tree.TreeControl('EntitiesTree');
  entities_tree.removeChildren();
  var root_text = goog.dom.$('id_entity_tree_select').value;
  if(response.length > 0)
  {
	altPopTree(entities_tree,response);
  } else {
    altPopTree(entities_tree,['No data for ' + root_text]);
  }
  entities_tree.render(goog.dom.$('id_entities_browser'));

}

function getEntityListingSuccess(response)
{
  entities_tree = new goog.ui.tree.TreeControl('EntitiesTree');
  if(response.length > 0)
  { 
    var entity_output = [goog.dom.$('id_entity_tree_select').value];
	entity_output.push(response)
    populateTreeFromDatastore(entities_tree,entity_output);
  } else {
    populateTreeFromDatastore(entities_tree,['No Data'])
  }
  entities_tree.render(goog.dom.$('id_entities_browser'));

}

function getEntities(entity_name) {
  server.getEntities(entity_name,getEntitiesSuccess);
}

function getEntitiesSuccess(response) {
  entities_tree = new goog.ui.tree.TreeControl('EntitiesTree');
  //alert("In getEntities Success " + response.length);
  if(response) {
    populateTree(entities_tree,response);
  }
  entities_tree.render(goog.dom.$('id_entities_browser'));
}

function populateTree(node,data) {
	  alert("data typeof=" + typeof data + "\ndata=" + data);
	  if(data['display_label']) {
	    node.setHtml(data['display_label']);
	  } else if(data['type_of']) {
	    
	    node.setHtml(data['type_of']);
	  } else if(typeof data == 'string'){ 
	     node.setHtml('<b>' + node.getHtml() + '</b>: ' + data); // else if(data['field']) {
	     //node.setHtml('<b>' + data['field'] + '</b>: ' + data['value']);
	  }
	  if(data['children']) {
	    var children = data['children'];
	    for(var i=0;i < children.length;i++) {
		  var newNode = node.getTree().createNode();
		  node.add(newNode);
		  populateTree(newNode,children[i]);
		}
	  }
	  if(data['properties'])
	  {
	    //alert("Data properties=" + data['properties'].length);
		var properties = data['properties'];
		//for(var i=0;i < properties.length;i++) { alert("IN PROPERTIES: " + properties[0]); }
	    for(var field in data['properties'])
		{
		  //var child = new atomic_property(name=field,value=data['properties'][field]);
		  var child = data['properties'][field];
		  var childNode = node.getTree().createNode();
		  if(typeof child == 'object') {
		    childNode.setHtml("<b>" + field + "</b>");
		    for(var value in child) {
			  var newChild = node.getTree().createNode();
			  newChild.setHtml('<b>' + field + '</b>');
			  childNode.add(newChild);
			  populateTree(newChild,child[value]);
			}
		  } else {
		    childNode.setHtml("<b>" + field + "</b> " + child);
		  }
		  node.add(childNode);
		  //alert("Field is " + field + '\ntype of '+ typeof field);
		  //createAltTree(childNode,child);
	    }
	  }
	  if(data['key']){
	    node.setClientData(data['key']);
	  }
	  
	}

function getWorkData()
{
  server.getWorks(getWorkDataSuccess);
}

function getWorkDataSuccess(response)
{
  var all_works = [];
  if(response)
  {
    //alert("IN RESPONSE " + response[0]['title']);
    all_works.push(response);
  }
  work_data = response;
  alert("Work data: " + work_data[0]['title']);
}

var sample_data = ['Titles',[['title',[['<b>key</b> ag1haWtpZG9jYXRhbG9nchALEgl0aXRsZUluZm8YvRwM'],
                                      ['<b>title</b> Best aikido: the fundamentals'],
						              ['<b>type</b> uniform'],
									  ['<b>associated works</b>',[['work1'],['work2']]]]],
							 ['title',[['<b>key</b> ag1haWtpZG44XRhbG9nchALEgl0aXRsZUluZm8YvRwM'],
                                      ['<b>title</b> Aikido exercises for teaching and training'],
						              ['<b>type</b> uniform']]]]];
									  
									  
var testData =
['Countries', [['A', [['Afghanistan'],
['Albania'],
['Algeria']]],
['B', [['Bahamas'],
['Bahrain'],
['Bangladesh'],
['Barbados'],
['Belarus']]]]];

function makeTree()
{
  entities_tree = new goog.ui.tree.TreeControl('Works');
  altPopTree(entities_tree,sample_data);
  // if(sample_data)
  // {
    // altPopTree(entities_tree,sample_data);
  // } else {
    // delay = new goog.Delay(makeTree,3000);
    // delay.start();
  // }
  entities_tree.render(goog.dom.$('id_entities_browser'));
}

function makeEntityTree(entity_name)
{
  getEntities(entity_name);
}

function altPopTree(node,data)
{
 var root = data[0];
 //alert(root + ' ' + data[1]);
 node.setHtml(root);
 if (data.length > 1)
 {
   var children = data[1];
   var childNotCollapsible = 3;
   for(var i=0;i < children.length;i++)
   {
     var child = children[i];
	 var childNode = node.getTree().createNode();
	 childNode.setClientData([root]);
     node.add(childNode);
	 altPopTree(childNode,child);
	 if(i == childNotCollapsible && child.length > 1)
      {
        childNode.setIsUserCollapsible(false);
        childNode.setExpanded(true);
        nonCollapseNode = childNode;
      }
   }
 }

}

function populateTreeFromDatastore(node, data)
{
 var root_element = data[0];
 alert("Root element is " + root_element);
 try 
 {
   // node.setClientData(root_element['key']);
    node.setHtml(root_element['created_on']);
  } catch(e) {
    node.setHtml(root_element);
  }
  if (data.length > 1)
  {
    var children = data[1];
	//alert("Children are " + children[0]['created_by']);
    var childNotCollapsible = 3;
    for(var i=0;i <= children.length;i++)
    {
	  var child = children[i];
      var childNode = node.getTree().createNode();
      node.add(childNode);
	  alert("Before recursive call " + child + "\nchildNode=" + childNode); 
      populateTreeFromDatastore(childNode,child);
      if(i == childNotCollapsible && children[i].length > 1)
      {
        childNode.setIsUserCollapsible(false);
        childNode.setExpanded(true);
        nonCollapseNode = childNode;
      }
    }
 }
}


function logEvent(e)
{
 var caption = e.target.value;
 if (typeof e.target.getCaption == 'function' && e.target.getCaption())
 {
  caption += ' (' + e.target.getCaption() + ')';
 }
 logger.info('"' + caption + '" dispached: ' + e.type);
 // if(caption.length > 1)
 // {
  // goog.dom.$('id_entity_props_title').innerHTML = '<h3>' + caption + '</h3>';
 // }
}

function browseHandler(e)
{
  var caption = e.target.value;
  if(e.type == 'change')
  {
     goog.dom.$('id_entity_props_title').innerHTML = '<h3>' + caption + '</h3>';
     makeEntityTree(caption);
  }
}

function addEntity()
{
  if(entities_tree.getSelectedItem())
  { 
    clipboardNode = entities_tree.getSelectedItem();
	alert("SELECT NODE: " + clipboardNode.getText());
	if(clipboardNode.getClientData())
	{
	  alert("IN ADD ENTITY: " + clipboardNode.getClientData()[0]);
	}
	
  }
}

function postPageLoad()
{
  EVENTS = goog.object.getValues(goog.ui.Component.EventType);
  logger = goog.debug.Logger.getLogger('demo');
  logconsole = new goog.debug.DivConsole(goog.dom.$('log'));
  logconsole.setCapturing(true);
  logger.fine('Listening for: ' + EVENTS.join(', ') + '.');
  goog.events.listen(goog.dom.$('enable_log'),goog.events.EventType.CLICK,
    function(e) {
      goog.style.showElement(goog.dom.$('log'),e.target.checked);
      logconsole.setCapturing(e.target.checked);
    }); 
  var entity_props_tbl = new goog.ui.TableSorter();
  var tbl_element= document.getElementById('id_entity_properties_tbl');
  //alert("entity_props_tbl" + entity_props_tbl + " tbl_element=" + tbl_element);
  entity_props_tbl.decorate(tbl_element);
  //entity_props_tbl.setSortFuction(1,goog.ui.TableSorter.alphaSort);

  // Hook up event handlers
  goog.events.listen(goog.dom.$('id_entity_tree_select'),EVENTS,browseHandler);
  goog.events.listen(goog.dom.$('id_entity_tree_select'),EVENTS,logEvent);
  //getWorkData();
  //makeTree();
}


